package com.xinyue.game.server.codec;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

public class DecodeHandler extends ChannelInboundHandlerAdapter {

	Logger logger = LoggerFactory.getLogger(DecodeHandler.class);
	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
		ByteBuf byteBuf = (ByteBuf) msg;
		int messageSize = byteBuf.readInt();
		GameMessage gameMessage = new GameMessage();
		GameMessageHeader header = new GameMessageHeader();
		header.read(byteBuf);
		gameMessage.setHeader(header);
		if (byteBuf.isReadable()) {
			byte[] body = new byte[byteBuf.readableBytes()];
			byteBuf.readBytes(body);
			gameMessage.setBody(body);
		}
		logger.debug("收到客户端请求，消息大小：{},消息号：{},序列号:{}", messageSize, header.getMessageId(), header.getSeqId());
		ctx.fireChannelRead(gameMessage);
	}
}
